<template>
  <div id="registerPage" class="full">
    <div class="main">
      <!-- 左侧图片-->
      <div class="main-left">
        <div class="logo">
          <el-image :src="LOGO" />
        </div>
        <el-config-provider size="large">
          <el-text style="margin: 5px auto" type="primary">
            <el-tag round>{{ type === "user" ? "用户" : "商家" }}</el-tag>
          </el-text>
          <el-text style="font-size: 32px" tag="b"
            >欢迎注册云选购物系统
          </el-text>
          <el-text type="primary">云选</el-text>
          <el-text type="primary">云上选购</el-text>
          <el-text type="primary">甄选品质</el-text>
        </el-config-provider>
      </div>
      <div class="main-right">
        <div class="business full">
          <!-- 导航条-->
          <el-steps
            :active="active"
            align-center
            class="main-steps"
            finish-status="success"
            process-status="finish"
          >
            <el-step title="账号信息" />
            <el-step title="基本信息" />
            <el-step title="完成" />
          </el-steps>
          <!-- 步骤1 -->
          <el-form
            v-show="active === 0"
            ref="registerRef"
            :model="registerData"
            :rules="rules"
            label-width="auto"
            style="padding: 10px"
          >
            <el-row :gutter="20">
              <el-col>
                <el-form-item label="账号" prop="username">
                  <el-input
                    v-model="registerData.username"
                    clearable
                    placeholder="请输入账号"
                  />
                </el-form-item>
              </el-col>

              <el-col>
                <el-form-item label="密码" prop="password">
                  <el-input
                    v-model="registerData.password"
                    clearable
                    placeholder="请输入密码"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model="registerData.confirmPassword"
                    clearable
                    placeholder="请确认密码"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="验证码" prop="captchaCode">
                  <captcha-input
                    :time-limit-flag="false"
                    @get:captcha:data="handleCaptchaData"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-button v-show="active === 0" type="success" @click="toLogin"
                  >返回登录
                </el-button>
                <el-button
                  v-show="active === 0"
                  type="primary"
                  @click="nextActive"
                  >下一项
                </el-button>
              </el-col>
            </el-row>
          </el-form>
          <!-- 步骤2-->
          <!-- 商家 -->
          <el-form
            v-if="active === 1 && type !== 'user'"
            ref="businessRef"
            :model="businessData"
            :rules="businessRules"
            class="full"
            label-width="auto"
            style="padding: 10px"
          >
            <el-row :gutter="20">
              <el-scrollbar max-height="400" style="width: 100%">
                <el-col>
                  <el-form-item label="店铺名" prop="storeName">
                    <el-input
                      v-model="businessData.storeName"
                      clearable
                      placeholder="请输入店铺名"
                    />
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="头像" prop="avatar">
                    <upload-image @update:url="handleAvatar" />
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="店铺简述" prop="sketch">
                    <el-input
                      v-model="businessData.sketch"
                      clearable
                      maxlength="50"
                      placeholder="请输入店铺简述"
                      show-word-limit
                      type="textarea"
                    />
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="联系号码" prop="phone">
                    <el-input
                      v-model="businessData.phone"
                      clearable
                      placeholder="请输入联系号码"
                    />
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item prop="email">
                    <template #label>
                      <span>联系邮箱</span>
                      <el-tooltip
                        content="邮箱将用于审核结果的发送，请验证是否能正常接收系统信息"
                        placement="left"
                      >
                        <el-icon style="margin: auto 0">
                          <InfoFilled />
                        </el-icon>
                      </el-tooltip>
                    </template>

                    <el-input
                      v-model="businessData.email"
                      clearable
                      placeholder="请输入联系邮箱"
                      style="width: 75%; margin-right: 5px"
                    />
                    <el-button type="primary">验证</el-button>
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="发货地" prop="place">
                    <el-cascader
                      v-model="placeValue"
                      :options="addressData"
                      :props="{
                        label: 'name',
                        value: 'name',
                      }"
                      class="full"
                      clearable
                      @change="handleChange"
                    />
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item prop="qualification">
                    <template #label>
                      <span>资质证明</span>
                      <el-tooltip
                        content="上传营业资质等信息审核，最多上传4张证明"
                        placement="left"
                      >
                        <el-icon style="margin: auto 0">
                          <InfoFilled />
                        </el-icon>
                      </el-tooltip>
                    </template>
                    <el-scrollbar :max-height="200">
                      <upload-image
                        :index="1"
                        :limit="3"
                        :urls="qualificationUrl"
                        style="width: 50%"
                        @update:url="handleQualificationUrl"
                      />
                    </el-scrollbar>
                  </el-form-item>
                </el-col>
              </el-scrollbar>
              <el-col style="margin-top: 5px">
                <el-button type="success" @click="backActive">上一项</el-button>
                <el-button type="primary" @click="handleSubmit(true)"
                  >提交审核
                </el-button>
              </el-col>
            </el-row>
          </el-form>

          <!-- 用户-->
          <el-form
            v-else-if="active === 1 && type === 'user'"
            ref="userRef"
            :model="userData"
            label-width="auto"
            style="padding: 10px"
          >
            <el-row :gutter="20">
              <el-scrollbar :max-height="300" style="width: 100%">
                <el-col>
                  <el-form-item label="姓名" prop="nickname">
                    <el-input
                      v-model="userData.nickname"
                      clearable
                      placeholder="请输入姓名"
                    />
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="userData.sex">
                      <el-radio :value="0" label="女" />
                      <el-radio :value="1" label="男" />
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="电话" prop="phone">
                    <el-input
                      v-model="userData.phone"
                      clearable
                      placeholder="请输入电话"
                    />
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="邮箱" prop="email">
                    <el-input
                      v-model="userData.email"
                      clearable
                      placeholder="请输入邮箱"
                    />
                  </el-form-item>
                </el-col>
                <el-col>
                  <el-form-item label="头像" prop="avatar">
                    <el-scrollbar class="full" height="200px">
                      <upload-image limit="1" @update:url="handleAvatar" />
                    </el-scrollbar>
                  </el-form-item>
                </el-col>
              </el-scrollbar>
            </el-row>
            <el-col style="margin-top: 5px">
              <el-button type="success" @click="backActive">上一项</el-button>
              <el-button type="primary" @click="handleSubmit">注册</el-button>
            </el-col>
          </el-form>
          <el-row v-show="active === 2">
            <el-col>
              <el-result
                :sub-title="
                  type === 'user'
                    ? '已完成注册，如需继续使用，请前往登录！'
                    : '已完成注册，店铺消息正在审核中，请留意邮件信息'
                "
                icon="success"
              >
                <template #extra>
                  <el-button type="primary" @click="toLogin"
                    >前往登录
                  </el-button>
                </template>
              </el-result>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <!-- ICP备案 -->
    <div class="icp-info">
      <el-space :size="'large'">
        <span>Copyright © 2024 阿良</span>
        <span>粤ICP备2024179481号</span>
      </el-space>
    </div>
  </div>
</template>

<script lang="ts" setup>
import LOGO from "@/assets/logo.png";
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import CaptchaInput from "@/components/CaptchaInput.vue";
import UploadImage from "@/components/UploadImage.vue";
import {
  BasicControllerService,
  BusinessControllerService,
  BusinessInsertDTO,
  UserInfoControllerService,
  UserInfoInsertDTO,
} from "@/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { InfoFilled } from "@element-plus/icons-vue";
import { addressData } from "@/assets/data/address";
//获取路由参数
const route = useRoute();
const type = route.query.type ?? "user";

interface Register {
  username?: string;
  password?: string;
  confirmPassword?: string;
  captchaCode?: string;
}

//第一步
const registerData = ref<Register>({});
const registerRef = ref();

//账户唯一性校验
async function validateUsername(rule: any, value: any, callback: any) {
  if (value) {
    await BasicControllerService.validateBusinessUsernameUsingPost(
      type !== "user",
      "",
      value
    ).then((res) => {
      if (res.code !== 200) {
        callback(res.data);
      } else {
        callback();
      }
    });
  }
}

//二次密码确认校验
function validatePwd(rule: any, value: any, callback: any) {
  if (value === "") {
    callback(new Error("请再次输入密码"));
    return;
  }
  if (value !== registerData.value.password) {
    callback(new Error("两次密码不一致"));
    return;
  }
  callback();
}

// 验证码校验
function validateCaptcha(rule: any, value: any, callback: any) {
  if (value === "") {
    callback(new Error("请输入验证码"));
    return;
  }
  if (value !== captchaCode.value) {
    callback(new Error("验证码不正确"));
    return;
  }
  callback();
}

const rules = {
  username: [
    {
      required: true,
      trigger: "blur",
      message: "请填入用户名",
    },
    {
      pattern: /[1-9]|[a-z]|[A-Z]/,
      message: "请输入英文或者数字",
      trigger: "blur",
    },
    { validator: validateUsername, trigger: "blur" },
  ],
  password: [
    {
      required: true,
      trigger: "blur",
      message: "请输入密码",
    },
    {
      min: 8,
      message: "密码不能小于8位",
      trigger: "blur",
    },
  ],
  confirmPassword: [
    {
      required: true,
      trigger: "blur",
      message: "请再次输入密码",
    },
    {
      min: 8,
      message: "密码不能小于8位",
      trigger: "blur",
    },
    { validator: validatePwd, trigger: "blur" },
  ],
  captchaCode: [
    {
      required: true,
      trigger: "blur",
      message: "请输入验证码",
    },
    { validator: validateCaptcha, trigger: "blur" },
  ],
};
// 处理验证码数据
const captchaCode = ref("");

function handleCaptchaData(data: any) {
  registerData.value.captchaCode = data.captchaCode;
  captchaCode.value = data.captchaKey;
}

//跳转路由
const router = useRouter();

function toLogin() {
  router.push("/basic/login");
}

//第二步
//商家
const businessData = ref<BusinessInsertDTO>({});
const active = ref(0);

// 前往下一步
function nextActive() {
  registerRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (type === "user") {
        userData.value.username = registerData.value.username;
        userData.value.password = registerData.value.password;
      } else {
        businessData.value.username = registerData.value.username;
        businessData.value.password = registerData.value.password;
      }
      if (active.value++ > 2) {
        active.value = 0;
      }
    } else {
      ElMessage.warning("验证未通过！");
    }
  });
}

const businessRef = ref(); //表单对象
// 表单规则
const businessRules = {
  email: [
    {
      required: true,
      trigger: "blur",
      message: "请输入邮箱",
    },
    {
      type: "email",
      trigger: "blur",
      message: "邮箱格式不对，请重新输入",
    },
  ],
  phone: [
    {
      required: true,
      trigger: "blur",
      message: "请输入手机号",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号码格式不正确",
      trigger: "blur",
    },
  ],
  qualification: [
    {
      required: true,
      trigger: "blur",
      message: "请上传资质证明",
    },
  ],
  place: [
    {
      required: true,
      trigger: "blur",
      message: "请选择发货地",
    },
  ],
};
const placeValue = ref([]);

//地址选项发生改变
const handleChange = (value: any) => {
  if (value) {
    placeValue.value = value;
    businessData.value.place = value.join(" ");
  }
};

// 处理资质上传
const qualificationUrl = ref<string[]>();

function handleQualificationUrl(urls: string[]) {
  if (urls.length > 0) {
    qualificationUrl.value = urls;
    businessData.value.qualification = JSON.stringify(urls);
  }
}

//用户
const userData = ref<UserInfoInsertDTO>({});
const userRef = ref();

// 处理头像
function handleAvatar(data: any) {
  if (data.length > 0) {
    if (type === "user") {
      userData.value.avatar = data[0];
    } else {
      businessData.value.avatar = data[0];
    }
  }
}

// 返回上一步
function backActive() {
  ElMessageBox.confirm("确认要返回上一步吗", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      if (active.value-- < 0) {
        active.value = 0;
      }
    })
    .catch(() => {
      ElMessage.info("已取消");
    });
}

// 处理提交
function handleSubmit(flag: boolean) {
  // 商家提交
  if (flag === true) {
    businessRef.value.validate((validate: boolean) => {
      if (validate) {
        BusinessControllerService.insertBusinessUsingPost(
          businessData.value
        ).then((res) => {
          ElMessage.success(res.data);
          //进入下一环节
          active.value++;
        });
      }
    });
  } else {
    userRef.value.validate((vali: boolean) => {
      if (vali) {
        UserInfoControllerService.insertUserInfoUsingPost(userData.value).then(
          (res) => {
            ElMessage.success(res.data);
            //进入下一环节
            active.value++;
          }
        );
      }
    });
  }
}
</script>

<style lang="scss" scoped>
#registerPage {
  background: linear-gradient(to bottom right, #ead6ee, #a0f1ea);
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;

  .main {
    min-height: 450px;
    background-color: white;
    margin: 0 auto;
    width: 70%;
    display: flex;
    border-radius: 16px;
    overflow: hidden;

    .main-left {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;

      .logo {
        display: flex;
        place-content: center center;
        width: 100%;
        height: 200px;
        padding: 10px;
      }
    }

    .main-right {
      flex: 1;

      & > div {
        margin-top: 20px;
      }

      .business {
        display: flex;
        flex-direction: column;

        form {
          flex: 1;
          width: 80%;
          margin: 10px auto;
        }
      }
    }
  }

  .icp-info {
    left: 40%;
    bottom: 10px;
    position: absolute;
  }
}

:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0 !important;
  margin: auto 0;
  background-color: #409eff;
  color: white;
}

:deep(.el-tabs__content) {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

// 让上传框和按钮保持一致
:deep(
    .el-scrollbar.full
      > .el-scrollbar__wrap.el-scrollbar__wrap--hidden-default
      > .el-scrollbar__view:last-child
      > div
  ) {
  display: inline-block;
}

:deep(.el-upload-list--picture-card) {
  --el-upload-list-picture-card-size: 145px;
}
</style>
